<?php @session_start();
//ini_set('error_reporting', 0);
ini_set('error_reporting', 1);
//ini_set('display_errors', false);
ini_set('display_errors', true);



function debug($sql, $array = false) {

	echo"<pre>";
	if ($array) {
		print_r($sql);
	}else {
		echo $sql;
	}

	echo"</pre>";

}


function getmicrotime(){
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();


################################  Componentes #################################
if(file_exists("admin/adodb/adodb.inc.php")){
	require_once("admin/adodb/adodb.inc.php");
	require_once("admin/adodb/colaboretohtml.inc.php");
}else {
	require_once("../admin/adodb/adodb.inc.php");
	require_once("../admin/adodb/colaboretohtml.inc.php");
}





$ADODB_FETCH_MODE = 3; // retorna ambos ex: $row[0] e $row["nome"]
$db = ADONewConnection("mysqli");


if ($db->Connect("localhost", "root", "" , "hotel_".$_SESSION["CLIENTE"])){
	//if ($db->Connect("localhost", "valeliv_colabore", "colabore" , "valeliv_".$_SESSION["CLIENTE"])){
	$_SESSION['ADOCnn'] = &$db;
}else{
	echo "<div class='aviso'><h2>Sistema em Manuten&ccedil;&atilde;o</h2>
         Em poucos minutos a aplica&ccedil;&atilde;o estar&aacute; on-line novamente.<br /><br />
         Caso o problema persista, entre em contato com o suporte da Empresa.<br /><hr /><u>Erro: </u>";
	echo $db->ErrorMsg();
	echo "<hr /></div>";
}



$url_externo = explode("/", $_SERVER["SCRIPT_NAME"]);
$conta_externo = (count($url_externo) - 1);

if (substr($url_externo[$conta_externo], 0, 7) != "externo") {

	$acessosFile = "com_acessos.jsp";
	if(file_exists("$acessosFile")){
		require_once("$acessosFile");
	}else{
		require_once("../$acessosFile");
	}

}


############################################ funcoes gerais #########################################

function setNomeCurto($texto){

	$arr = explode(" ",$texto);
	if (count($arr) > 1) {
		$formatado = $arr[0]."_".$arr[1][0].">";
	}else{
		$formatado = $arr[0].">";
	}


	return $formatado;
}


function _t($string) // converte tudo para allhtmlentities
{
	return preg_replace('/[^\x00-\x7F]/e', '"&#".ord("$0").";"', $string);
}


function _t2($string){

	$arr = array(
	'cad' => 'Cadastros',
	'alt' => 'Altera&ccedil;&otilde;es e Exclus&otilde;es',
	'pesq' => 'Pesquisas',
	'reservas' => 'Reservas',
	'rel' => 'Relat&oacute;rios',
	'config' => 'Configura&ccedil;&otilde;es'
	);
	return $arr[$string];
}



function formataData($data, $gravacao=false){
	if($gravacao){
		list($dia,$mes,$ano) = explode("/", $data);
		return $ano."-".$mes."-".$dia;

	}else{
		list($ano,$mes,$dia) = explode("-", $data);
		$dia = substr($dia,0,2);
		$dataFormatada = "$dia/$mes/$ano";

		if(trim($dataFormatada) == "//"){
			return null;
		}else{
			return $dataFormatada;
		}
	}
}


function formataDataHora($data){
	list($ano,$mes,$dia) = explode("-", $data);
	$dia = substr($dia,0,2);

	$dataFormatada = "$dia/$mes/$ano";

	list($H,$m,$s) = explode(":", $data);
	$H =  substr($H,-2,2);

	$horaFormatada = "$H:$m";

	if(trim($dataFormatada) == "//"){
		return null;
	}else{
		return "$dataFormatada $horaFormatada";
	}
}



function formataValor($valor, $cifra=false, $gravacao=false){

	if ($gravacao == false) {

		if (trim($valor) == "" or trim($valor) == 0) {
			$formatted = "0,00";
		}else{
			//$formatted = sprintf("%01.2f", $valor);
			$formatted = number_format($valor, 2, ',', '.');
		}


		if ($cifra == true) {
			return "R$ $formatted";
		}else {
			return $formatted;
		}

	}else{

		return str_replace(",",".",str_replace(".","",$valor));

	}

}


function somaDias($dia=null,$mes=null,$ano=null, $somadias, $formato="Y-m-d") {

	if ($dia == null) {
		$data  = date($formato, mktime(0, 0, 0, date("m")  , date("d")+$somadias, date("Y")));
	}else{
		$data  = date($formato, mktime(0, 0, 0, $mes  , $dia+$somadias, $ano));
	}

	return $data;

}

function isEmail($e){
	if(eregi("^[a-zA-Z0-9]+[_a-zA-Z0-9-]*(\.[_a-z0-9-]+)*@[a-z??????0-9]+(-[a-z??????0-9]+)*(\.[a-z??????0-9-]+)*(\.[a-z]{2,4})$", $e)){
		return TRUE;
	}else{
		return FALSE;
	}
}




function removeHTML($string){

	$trans = array("<b>" => "", "</b>" => "","<i>" => "", "</i>" => "",
	"<u>" => "", "</u>" => "","<br>" => "", "<br />" => "",
	"<h1>" => "", "</h1>" => "","<h2>" => "", "</h2>" => "",
	"<h3>" => "", "</h3>" => "", "<h4>" => "", "</h4>" => "");

	return strtr("$string", $trans);
}











function dif_dias($start_date, $end_date){ //aaaammdd
	//	echo "$start_date, $end_date";
	$resultado=((strtotime($start_date) - strtotime($end_date))/86400);
	return (int)$resultado;
}

function dif_dias_menos_sab_e_dom($start_date, $end_date){ // aaaammdd
	$resultado=((strtotime($start_date) - strtotime($end_date))/86400);
	$ano=substr($start_date,0,4);
	$mes=substr($start_date,4,2);
	$dia=substr($start_date,6,2);

	$vezes=abs($resultado);
	$dia_descontados=0;
	//echo "$vezes<BR>";
	for($n=1;$n<=$vezes;$n++){
		$sab_ou_dom=date("w", mktime(0, 0, 0, $mes, $dia+$n, $ano));
		if($sab_ou_dom==0 or $sab_ou_dom==6){ $dia_descontados++; }
		// echo "$sab_ou_dom - $dia_descontados<BR>";
	}

	$resultado =( $vezes - $dia_descontados);

	return (int)$resultado;


}





#########################################  funcoes magicas #########################################



function getModoExibicao(){
	return acessoMenu("modo_exibicao", $_SESSION["MODULO_"]);
}


##### incrementa +1 ao maior codigo na tabela #####
function incremento($campo,$tabela,$numeracao) {
	if($numeracao==1){
		$row = $_SESSION['ADOCnn']->Execute("select max($campo) from $tabela where id_hostel= $_SESSION[ID_HOSTEL_]");
		$incrementa	= ($row->fields[0] + 1);
	}else{
		$row = $_SESSION['ADOCnn']->Execute("select max($campo) from $tabela");
		$incrementa	= ($row->fields[0] + 1);
	}
	return $incrementa;

}


function retorna_quem_cad($codigo, $id_pessoa=null){
	$sql="select id_pessoa, nome_pessoa from  pes_pessoas where id_pessoa = $codigo";
	$exec=$_SESSION['ADOCnn']->Execute("$sql");


	if ($id_pessoa == $exec->fields[0]) {
		return "<i>Auto-Cadastro <br>Site</i>";
	}else{
		return $exec->fields[1];
	}

}


function getHorario($horario="E", $intervalos=false) {
	/*
	if($horario=="E"){
	if ($intervalos) {$campo = "(hr_ini_diaria + INTERVAL 1 SECOND)";}
	$row = $_SESSION['ADOCnn']->Execute("select $intervalos from hostel_configuracao where id_hostel= $_SESSION[ID_HOSTEL_]");
	return $row->fields[0];
	}elseif($horario=="S"){
	if ($intervalos) {$campo = "(hr_fim_diaria - INTERVAL 1 SECOND)";}
	$row = $_SESSION['ADOCnn']->Execute("select $intervalos from hostel_configuracao where id_hostel= $_SESSION[ID_HOSTEL_]");
	return $row->fields[0];
	}
	*/

	if($horario=="E"){

		$row = $_SESSION['ADOCnn']->Execute("select hr_ini_diaria from hostel_configuracao where id_hostel= $_SESSION[ID_HOSTEL_]");
		$hora = $row->fields[0];
		if ($intervalos) {
			$campos = explode(":",$row->fields[0]);
			$hora = date("H:i:s",mktime($campos[0],$campos[1],$campos[2]-1,0,0,0));
		}
		return $hora;
	}elseif($horario=="S"){

		$row = $_SESSION['ADOCnn']->Execute("select hr_fim_diaria from hostel_configuracao where id_hostel= $_SESSION[ID_HOSTEL_]");
		$hora = $row->fields[0];
		if ($intervalos) {
			$campos = explode(":",$row->fields[0]);
			$hora = date("H:i:s",mktime($campos[0],$campos[1],$campos[2]+1,0,0,0));
		}
		return $hora;
	}

}



// utilizado para validar dataf menor q datai
function validaDatafDatai($datai,$dataf) { // dd/mm/yyyy

	list($vddi,$vmmi,$vaai) = explode("/",$datai);
	list($vddf,$vmmf,$vaaf) = explode("/",$dataf);

	if ($vaaf.$vmmf.$vddf <= $vaai.$vmmi.$vddi) {
		//echo $vaaf.$vmmf.$vddf."<=".$vaai.$vmmi.$vddi;
		die("<div class='aviso'>N&atilde;o &eacute; poss&iacute;vel efetuar reservas com 'data final da reserva' menor ou igual a 'data inicial da reserva'.</div>");
	}else{
		return null;
	}
}


function getDtCancelaAuto() {

	$row = $_SESSION['ADOCnn']->Execute("select tempo_max_reserva from hostel_configuracao where id_hostel={$_SESSION["ID_HOSTEL_"]}");
	$tempo_max_reserva = $row->fields["tempo_max_reserva"];

	$hora = date("d/m/Y H:i:s",mktime(date("H"),date("i"),date("i"),date("m"),date("d")+$tempo_max_reserva,date("Y")));
	return $hora;

}





function autoCancelaReservas(){

	if ($_SESSION["ID_HOSTEL_"]){
		$sql_0="select tempo_max_reserva from hostel_configuracao where id_hostel = ". $_SESSION["ID_HOSTEL_"];
		$linha=$_SESSION['ADOCnn']->Execute("$sql_0");
		$dias_reserva = (int)$linha->fields[0];
		$data_cancelamento  = date("Y-m-d", mktime(0, 0, 0, date("m")  , date("d")- $dias_reserva, date("Y")));


		if(date("Y-m-d") !== $data_cancelamento){
			// debug renoldi echo date("Y-m-d")."<hr>". $data_cancelamento;
			$sql_1="
                 update hostel_reservas a set
                    a.data_baixa = '".date("Y-m-d")."',
                    a.ref_quem_baixa = ". $_SESSION["loginCK_"] .",
                    a.obs_reserva = 'cancelada por expirar o prazo de $dias_reserva dias',
                    a.cancelada = 1
                 where
                    a.data_cad_reserva < '$data_cancelamento'
                    ";
			$ln=$_SESSION['ADOCnn']->Execute("$sql_1");

			return true;
		}else{
			return null;
		}
	}else{
		return false;
	}

}


function exibeNomeTabela($tabela) {

	$t = explode("_",$tabela);
	return strtoupper($t[1]);

}


/*
function reservasDoMembro($codigo, $num_resultado, $detalhes=false, $disponibilidade=false){
if($detalhes == true){
$addsql= ",`hostel_reservas`.`obs_reserva`,
`hostel_reservas`.`ref_quem_cad`";
$addtr = "<td>Observa&ccedil;&atilde;o</td><td>Funcion&aacute;rio que reservou</td>";
}

if($disponibilidade == true){
$addsql2= "and
((`hostel_reservas`.ref_quem_baixa is null) and (`hostel_reservas`.cancelada is null))";
}



$sql = "

SELECT
`bibl_reservadas`.`ref_midia`,
`bibl_midias`.`tombo`,
`bibl_midias`.`titulo`,
`bibl_reservadas`.`data_cad_reserva`,
`bibl_reservadas`.`cancelada`

$addsql
FROM
`bibl_reservadas`
inner Join `bibl_midias` ON (`bibl_reservadas`.`ref_midia` = `bibl_midias`.`cod_midia`)
where
(`bibl_reservadas`.ref_membro = $codigo)
$addsql2
order by `bibl_reservadas`.`data_cad_reserva` desc
limit 0, $num_resultado
";

//echo $sql;

$linha=$_SESSION['ADOCnn']->Execute("$sql");

echo"<fieldset class='subgrupo'>
<legend>&Uacute;ltimas Reservas do Membro:</legend>
<table>
<tr class='titulo2'>
<td width=15>Tombo</td>";
if($disponibilidade == true){echo"<td>Dispon&iacute;vel</td>";}
echo"<td>T&iacute;tulo</td>
<td>Data Cad. Reserva</td>
$addtr
</tr>";
$n = 0;
if($linha->RecordCount() != 0 ){
while(!$linha->EOF){

$data1 =  formataData($linha->fields[3]);
$class = $linha->fields[4] ? "cancelada1":" ";

if($detalhes == true){
$addtd = "<td class='$class'>".formataData($linha->fields[5])."</td><td>".retorna_quem_cad($linha->fields[6], $codigo)."</td>";
}

echo "<tr>
<td  class='$class' width=15>".$linha->fields[1]."</td>";

if($disponibilidade == true){
echo"<td>".verificaLiberada($linha->fields[0],$codigo)."&nbsp;</td>";
}

echo "
<td class='$class'>"._t($linha->fields[2])."</td>
<td class='$class'>$data1</td>
$addtd
</tr>
";
$n++;

$linha->MoveNext();
}
}
echo "</table><br>
<b>Total de Resultados:</b> <u>$n</u>
</fieldset>
";


}

*/


function header_impressao(){
	echo'
        <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
        <html>
        <head>
        <title>COLABORE Hotelaria - Sistema de Controle Hoteleiro</title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <meta name="description"content="COLABORE Hotelaria - Sistema de Controle Hoteleiro">
        <meta name="keywords" content="COLABORE Hotelaria - Sistema de Controle Hoteleiro">
        <meta name="robots" content="ALL">
        <meta name="author" content="Renoldi">
        <meta name="language" content="pt-br">
        <style type="text/css"  media="all" title="COLABORE Hotelaria_all" id="all">@import url("../css2/print.css");</style>
        <style type="text/css"  media="print" title="COLABORE Hotelaria_print" id="impressao">@import url("../css2/print.css");</style>
        <script type="text/javascript" src="css2/div.js"></script>
        </head>
        <body bgcolor="#FFFFFF">
        ';

}




function acessoMenu($campo, $modulo='hotelaria', $id_hostel = null ) {
	if ($id_hostel == null) {
		$id_hostel = ((session_is_registered($_SESSION["ID_HOSTEL_"]) ? $_SESSION["ID_HOSTEL_"] : 1));
	}
	$sql="select    $campo from  hostel_configuracao   where id_hostel = $id_hostel ";
	$montamenu = $_SESSION['ADOCnn']->Execute("$sql");
	return $montamenu->fields[0];
}


###inicio gera cor para os graficos ################################
//This page contains an array of colors to be used as default set of colors for FusionCharts
//arr_FCColors is the array that would contain the hex code of colors
//ALL COLORS HEX CODES TO BE USED WITHOUT #


//We also initiate a counter variable to help us cyclically rotate through
//the array of colors.
$FC_ColorCounter=0;

$arr_FCColors[0] = "1941A5" ;//Dark Blue
$arr_FCColors[1] = "AFD8F8";
$arr_FCColors[2] = "F6BD0F";
$arr_FCColors[3] = "8BBA00";
$arr_FCColors[4] = "A66EDD";
$arr_FCColors[5] = "F984A1" ;
$arr_FCColors[6] = "CCCC00" ;//Chrome Yellow+Green
$arr_FCColors[7] = "999999" ;//Grey
$arr_FCColors[8] = "0099CC" ;//Blue Shade
$arr_FCColors[9] = "FF0000" ;//Bright Red
$arr_FCColors[10] = "006F00" ;//Dark Green
$arr_FCColors[11] = "0099FF"; //Blue (Light)
$arr_FCColors[12] = "FF66CC" ;//Dark Pink
$arr_FCColors[13] = "669966" ;//Dirty green
$arr_FCColors[14] = "7C7CB4" ;//Violet shade of blue
$arr_FCColors[15] = "FF9933" ;//Orange
$arr_FCColors[16] = "9900FF" ;//Violet
$arr_FCColors[17] = "99FFCC" ;//Blue+Green Light
$arr_FCColors[18] = "CCCCFF" ;//Light violet
$arr_FCColors[19] = "669900" ;//Shade of green

//getFCColor method helps return a color from arr_FCColors array. It uses
//cyclic iteration to return a color from a given index. The index value is
//maintained in FC_ColorCounter

function getFCColor() {
	//accessing the global variables
	global $FC_ColorCounter;
	global $arr_FCColors;

	//Update index
	$FC_ColorCounter++;
	//Return color
	return($arr_FCColors[$FC_ColorCounter % count($arr_FCColors)]);
}
###fim gera cor para os graficos ################################


?>
